﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using TAXILISM.Class;
using System.Windows.Media.Imaging;
using System.Collections.Specialized;

using System.Threading;
using System.Windows.Threading;
using Microsoft.Phone.Net.NetworkInformation;
using TAXILISM.HelperClasses;
using RedBit.OAuthLibrary.Twitter;
using RedBit.WindowsPhone.Samples;
using RedBit.OAuthLibrary;
using RedBit;
using System.Xml.Linq;
using System.Xml;
using Microsoft.Phone.Tasks;
using System.Windows.Resources;
using Facebook;
using System.IO;
using Microsoft.Xna.Framework.Media;
using TAXILISM.TaxiWebService;
using System.Windows.Media.Imaging;
using System.Device.Location;
using System.Text;

namespace TAXILISM
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        Thread t4;
        CallTaxiNumber TaxNum = new CallTaxiNumber();
        public MainPage()
        {
            InitializeComponent();
            
            DataContext = App.ViewModel;
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);

            if (NetworkInterface.NetworkInterfaceType!= Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.None)
            {
                try
                {
                    TaxNum.feedTaxi();
                    TaxNum.getRecent();
                    TaxNum.getVoteable();
                    TaxNum.getRateShow();
                    Dispatcher.BeginInvoke(() =>
                    {
                        t5 = new Thread(taxilistrate_check);
                        t5.Start();
                    });
                }
                catch
                {
                }
            }
            else
            {
                TaxNum.feedTaxi();
                TaxNum.getRecent();
                CallingListBox.ItemsSource = null;
                CallingListBox.ItemsSource = TaxNum.taxi_list;
                RecentCallListBox.ItemsSource = null;
                if (TaxNum.taxRecent.Count == 0)
                {
                    RecentCallListBox.IsEnabled = false;
                    List<TaxiList> nodata = new List<TaxiList>();
                    TaxiList xxx = new TaxiList();
                    xxx.Data_taxName = "xxxxxxxxxxxxx";
                    xxx.Data_taxPhone = "xxxxxxxxxxxxx";
                    nodata.Add(xxx);
                    RecentCallListBox.ItemsSource = nodata;
                }
                else
                {
                    RecentCallListBox.IsEnabled = true;
                    foreach (TaxiList list in TaxNum.taxi_list)
                    {
                        if (list.Data_id == idRecent.ToString())
                        {
                            List<TaxiList> reallist = new List<TaxiList>();
                            reallist.Add(list);
                            RecentCallListBox.ItemsSource = reallist;
                        }
                    }

                }
            }


            SuggestText.Visibility = Visibility.Collapsed;

            cam = new CameraCaptureTask();
            cam.Completed += new EventHandler<Microsoft.Phone.Tasks.PhotoResult>(cam_Completed);

            twLogin.Navigated += BrowserNavigated;
            twLogin.ScriptNotify += BrowserScriptNotify;
            twLogin.Loaded += BrowserLoaded;

            List<taxiColor> colorlist = new List<taxiColor>();
            CallTaxiColor taxColorCall = new CallTaxiColor();
            taxColorCall.feedTaxiCol();

            foreach (TaxiListCol rs in taxColorCall.taxi_list_col) {
                if (rs.Data_col21_col.Equals("null"))
                {
                    colorlist.Add(new taxiColor { color1 = new SolidColorBrush(Color.FromArgb(255, Convert.ToByte(rs.Data_col11_col), Convert.ToByte(rs.Data_col12_col), Convert.ToByte(rs.Data_col13_col))), colorName = rs.Data_name_col });
                }
                else 
                {
                    colorlist.Add(new taxiColor { color1 = new SolidColorBrush(Color.FromArgb(255, Convert.ToByte(rs.Data_col11_col), Convert.ToByte(rs.Data_col12_col), Convert.ToByte(rs.Data_col13_col))), color2 = new SolidColorBrush(Color.FromArgb(255, Convert.ToByte(rs.Data_col21_col), Convert.ToByte(rs.Data_col22_col), Convert.ToByte(rs.Data_col23_col))), colorName = rs.Data_name_col });
                }
            }

            taxiColorPicker.ItemsSource = colorlist;
            
        }

        public void taxilist_check()
        {
            while (TaxNum.cnt_client != 0||TaxNum.cnt_client2!=0)
            {
                Thread.Sleep(100);
            }

            Dispatcher.BeginInvoke(() =>
            {
                //TaxNum.getRateShow();
                TaxNum.getRecent();
                TaxNum.getVoteable();
                CallingListBox.ItemsSource = null;

                CallingListBox.ItemsSource = TaxNum.taxi_list;

                RecentCallListBox.ItemsSource = null;
                if (TaxNum.taxRecent.Count == 0)
                {
                    RecentCallListBox.IsEnabled = false;
                    List<TaxiList> nodata = new List<TaxiList>();
                    TaxiList xxx = new TaxiList();
                    xxx.Data_taxName = "xxxxxxxxxxxxx";
                    xxx.Data_taxPhone = "xxxxxxxxxxxxx";
                    nodata.Add(xxx);
                    RecentCallListBox.ItemsSource = nodata;

                }
                else
                {
                    RecentCallListBox.IsEnabled = true;
                    
                    foreach(TaxiList list in TaxNum.taxi_list){
                        if(list.Data_id == TaxNum.taxRecent.First().Data_id.ToString()){
                            idRecent = Convert.ToInt32(TaxNum.taxRecent.First().Data_id);
                            List<TaxiList> reallist = new List<TaxiList>();
                            reallist.Add(list);
                            RecentCallListBox.ItemsSource = reallist;
                        }
                    }
                    
                }
            });
            t4.Join();
        }

        public void taxilistrate_check()
        {
            while (TaxNum.cnt_client != 0 || TaxNum.cnt_client2 != 0)
            {
                Thread.Sleep(100);
            }
            Dispatcher.BeginInvoke(() =>
            {
                TaxNum.getRecent();
                TaxNum.getVoteable();
                TaxNum.getRateShow();
                Dispatcher.BeginInvoke(() =>
                {
                    t4 = new Thread(taxilist_check);
                    t4.Start();
                });
            });
            t5.Join();
        }

        // Load data for the ViewModel Items
        bool checkAllowLocation;
        LocationAllow la = new LocationAllow();
        public int goSetting = 0; 

        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.LoadData();
                m_fbPost = new FBWallNewsPost(true);
            }

            la.getAllow();
            checkAllowLocation = Convert.ToBoolean(la.status);

            if (goSetting == 0)
            {
                if (la.status == null || la.status == "false")
                {
                    MessageBoxResult result = MessageBox.Show("If you allow Location Service on this application, You can use your current location to calculate a taxi fare. This application only uses your location data as an input of search box and doesn't share your location data anyway.", "Allow the application to use your location?", MessageBoxButton.OKCancel);
                    if (result == MessageBoxResult.OK)
                    {
                        la.putAllow("true");
                        la.getAllow();
                        checkAllowLocation = Convert.ToBoolean(la.status);
                    }
                    else
                    {
                        la.putAllow("false");
                        la.getAllow();
                        checkAllowLocation = Convert.ToBoolean(la.status);
                    }
                }
            }
        }
        
        string taxCol;
        private void taxiColorPicker_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            taxiColor data = (sender as ListPicker).SelectedItem as taxiColor;
            taxCol = data.colorName;
        }

        #region FacebookShare
        private FBWallNewsPost m_fbPost;
        private WebClient m_wcPostMessage;
        private FacebookClient fbClient;
       
        private void fbShareBut_Click(object sender, RoutedEventArgs e)
        {
            if (this.publishImage == "" && taxiNumber.Text == "")
            {
                MessageBox.Show("Please input or capture a taxi plate number");
                twBlock.Visibility = Visibility.Collapsed;
                return;
            }

            fbLogin.Visibility = System.Windows.Visibility.Visible;
            fbLogin.Navigate(FBUris.GetLoginUri());
        }

        private int check_Security=0;
        private void fbLogin_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            string strLoweredAddress = e.Uri.OriginalString.ToLower();
            if (strLoweredAddress.StartsWith("https://www.facebook.com/connect/login_success.html?code="))
            {
                //txtStatus.Text = "Trying to retrieve access token";
                fbLogin.Visibility = System.Windows.Visibility.Collapsed;
                fbLogin.Navigate(FBUris.GetTokenLoadUri(e.Uri.OriginalString.Substring(57)));
                check_Security = 1;
                return;
            }
            else if (strLoweredAddress.StartsWith("http://www.facebook.com/connect/login_success.html?code="))
            {
                fbLogin.Visibility = System.Windows.Visibility.Collapsed;
                fbLogin.Navigate(FBUris.GetTokenLoadUriNoSecurity(e.Uri.OriginalString.Substring(56)));
                check_Security = 0;
                return;
            }
            string strTest = fbLogin.SaveToString();
            if (strTest.Contains("access_token"))
            {
                int nPos = strTest.IndexOf("access_token");
                string strPart = strTest.Substring(nPos + 13);
                nPos = strPart.IndexOf("</pre>");
                strPart = strPart.Substring(0, nPos);
                //REMOVE EXPIRES IF FOUND!
                nPos = strPart.IndexOf("&amp;expires=");
                if (nPos != -1)
                {
                    strPart = strPart.Substring(0, nPos);
                }
                App.AccessToken = strPart;
                var result = MessageBox.Show("Are you sure?", "Share Facebook", MessageBoxButton.OKCancel);
                if (result == MessageBoxResult.OK)
                {
                    postToWall();
                }
                else
                {
                    return;
                }
                return;
            }

        }

        StreamResourceInfo sri = null;
        private void postToWall()
        {
            fbClient = new FacebookClient(App.AccessToken);
            if (m_wcPostMessage == null)
            {
                m_wcPostMessage = new WebClient();
                m_wcPostMessage.UploadStringCompleted += new UploadStringCompletedEventHandler(m_wcPostMessage_UploadStringCompleted);
            }
            if (this.publishImage != "")
            {
                    string imageName = "";

                    imageName = this.publishImage;

                    string imageText;
                    if (!taxiNumber.Text.Equals(""))
                    {
                        imageText = "กำลังอยู่บนรถแท๊กซี่ " + taxCol + " : " + taxiNumber.Text;
                    }
                    else 
                    {
                        imageText = "กำลังอยู่บนรถแท๊กซี่ " + taxCol ;
                    }

                    try
                    {
                        byte[] imageData = new byte[sri.Stream.Length];
                        sri.Stream.Read(imageData, 0, System.Convert.ToInt32(sri.Stream.Length));

                        FacebookMediaObject fbUpload = new FacebookMediaObject
                        {
                            FileName = imageName,
                            ContentType = "image/jpg"
                        };
                        fbUpload.SetValue(imageData);


                        IDictionary<string, object> parameters = new Dictionary<string, object>();
                        parameters.Add("access_token", App.AccessToken);
                        parameters.Add("source", fbUpload);
                        parameters.Add("message", imageText);

                        fbClient.PostAsync("/me" + "/photos", parameters);

                        MessageBox.Show("Post completed");
                        fbLogin.Visibility = System.Windows.Visibility.Collapsed;
                        captureBlock.Background = null;
                        this.publishImage = "";
                        taxiNumber.Text = "";
                        
                        return;
                    }
                    catch (Exception error)
                    {
                        MessageBox.Show("Sorry, there's an error occured, please try again.");
                    }
                

            }

            else
            {
                try
                {
                    if (!taxiNumber.Text.Equals(""))
                    {
                        if (check_Security == 1)
                        {
                            m_wcPostMessage.UploadStringAsync(FBUris.GetPostMessageUri(), "POST", m_fbPost.GetPostParameters(App.AccessToken, taxiNumber.Text, taxCol));
                        }
                        else if (check_Security == 0)
                        {
                            m_wcPostMessage.UploadStringAsync(FBUris.GetPostMessageUriNoSecurity(), "POST", m_fbPost.GetPostParameters(App.AccessToken, taxiNumber.Text, taxCol));
                        }

                    }
                    else
                    {
                        MessageBox.Show("Please input or capture a taxi plate number");
                        fbLogin.Visibility = System.Windows.Visibility.Collapsed;
                    }
                }

                catch (Exception eX)
                {
                    MessageBox.Show("Sorry, there's an error occured, please try again.");
                }
            }
        }

        void m_fbPost_PostStatus(object sender, FBPhotoPost.PostStatusEventArgs e)
        {
            MessageBox.Show(e.MessageHeader);
            MessageBox.Show(e.MessageContents);
        }

        void m_wcPostMessage_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show("Cannot Duplicate Post");
                fbLogin.Visibility = System.Windows.Visibility.Collapsed;
                
                return;
            }
            try
            {
                MessageBox.Show("Post completed");
                fbLogin.Visibility = System.Windows.Visibility.Collapsed;
                taxiNumber.Text = "";
                return;
            }
            catch (Exception eX)
            {
                MessageBox.Show("Sorry, there's an error occured, please try again.");
            }
        }
        #endregion

        #region Twitter
        private bool m_browserLoaded = false;
        public TwitterOAuth m_twitterOAuth;
        public TwitterOAuth m_twitterOAuth2;

        void BrowserNavigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            //show the web browser when the twitter auth page loads          
            twLogin.Visibility = System.Windows.Visibility.Visible;
            //textBlock1.Visibility = System.Windows.Visibility.Collapsed;
            ////textBox1.Visibility = System.Windows.Visibility.Visible;
            // button1.Visibility = System.Windows.Visibility.Visible;
            //unhook the navigated event

            twLogin.Navigated -= BrowserNavigated;
        }

        void BrowserScriptNotify(object sender, NotifyEventArgs e)
        {

            try
            {
                Uri uri = new Uri(e.Value);
                Dictionary<string, string> results = Helpers.ParseQueryString(uri.Query);
                foreach (var item in results)
                {
                    if (item.Key.Equals("oauth_verifier"))
                        m_twitterOAuth.Verifier = item.Value;
                }

                this.Dispatcher.BeginInvoke(() =>
                {
                    twLogin.Visibility = System.Windows.Visibility.Collapsed;
                });

                //now that we have the verifier get the access token
                OAuth.GetAccessToken(m_twitterOAuth.AccessTokenUrl,
                    m_twitterOAuth.ConsumerKey,
                    m_twitterOAuth.ConsumerSecret,
                    m_twitterOAuth.Token,
                    m_twitterOAuth.TokenSecret,
                    new EventHandler<OAuthEventArgs>((obj, args) =>
                    {
                        //handler when the get access token call returns
                        if (args.IsError)
                            this.Dispatcher.BeginInvoke(() => MessageBox.Show(args.ErrorMessage));
                        else
                        {
                            //extract the items
                            results = Helpers.ParseQueryString(args.Response);
                            foreach (var item in results)
                            {
                                if (item.Key.Equals("oauth_token"))
                                    m_twitterOAuth.Token = item.Value;
                                else if (item.Key.Equals("oauth_token_secret"))
                                    m_twitterOAuth.TokenSecret = item.Value;
                                else if (item.Key.Equals("user_id"))
                                    m_twitterOAuth.UserId = item.Value;
                                else if (item.Key.Equals("screen_name"))
                                    m_twitterOAuth.ScreenName = item.Value;
                            }

                            //update the label
                            this.Dispatcher.BeginInvoke(() =>
                            {
                                //  textBlock1.Text = string.Format("Successfully authenticated!! Signed in as {0} with userId of {1}", m_twitterOAuth.ScreenName, m_twitterOAuth.UserId);
                                //   MessageBox.Show(textBlock1.Text, "Authorized for Twitter", MessageBoxButton.OK);
                                // btnSignOut.Visibility = btnPostTweet.Visibility = txtTweet.Visibility = System.Windows.Visibility.Visible;
                                //textBlock1.Visibility = System.Windows.Visibility.Collapsed;
                                // popTweet.IsOpen = false;
                            });
                            //SaveTwitterOAuth();

                        }
                    }));
            }
            catch (Exception ex)
            {
                this.Dispatcher.BeginInvoke(() => MessageBox.Show(ex.Message));
            }
        }

        void BrowserLoaded(object sender, RoutedEventArgs e)
        {
            m_browserLoaded = true;
        }

        private void twShareBut_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (this.publishImage == "" && taxiNumber.Text == "")
            {
                MessageBox.Show("Please input or capture a taxi plate number");
                twBlock.Visibility = Visibility.Collapsed;
                return;
            }
            //if (!taxiNumber.Text.Equals(""))
            //{
            m_twitterOAuth = null;
            m_twitterOAuth = ApplicationSettings.TwitterOAuthAppSettings;
            if (m_twitterOAuth == null)
            {
                m_twitterOAuth = new TwitterOAuth();
                m_twitterOAuth.ConsumerKey = "dbP6dStqV6mBlzzVUNObw";
                m_twitterOAuth.ConsumerSecret = "f9Qc4gt9Ph3JgAEK2PV74gFGROJMasYB4YhgYd9GPAE";
                GetRequestToken();
            }
            else
            {
                OAuth.GetProtectedResource(m_twitterOAuth.VerifyCredentialsUrl, "GET", m_twitterOAuth.ConsumerKey, m_twitterOAuth.ConsumerSecret, m_twitterOAuth.Token, m_twitterOAuth.TokenSecret,
                    new EventHandler<OAuthEventArgs>((obj, args) =>
                    {
                        //call return so verify what the response is 
                        if (args.IsError)
                        {
                            GetRequestToken();
                        }
                        else
                        {
                            Dispatcher.BeginInvoke(() =>
                            {
                                var result = MessageBox.Show("Are you sure?", "Share Tweet", MessageBoxButton.OKCancel);
                                if (result == MessageBoxResult.OK)
                                {
                                    if (this.publishImage != "")
                                    {
                                        TweetPhotos();
                                    }
                                    else
                                    {
                                        if (!taxiNumber.Text.Equals(""))
                                        {
                                            PostTweet();
                                        }
                                        else
                                        {
                                            MessageBox.Show("Please input or capture a taxi plate number");
                                            twBlock.Visibility = Visibility.Collapsed;
                                        }
                                    }
                                }
                                else
                                {
                                    twBlock.Visibility = Visibility.Collapsed;
                                }
                            });
                        }
                    }));
            }
        }

        private void GetRequestToken()
        {
            OAuth.GetRequestToken(m_twitterOAuth.RequestTokenUrl,
                m_twitterOAuth.ConsumerKey,
                m_twitterOAuth.ConsumerSecret,
                new EventHandler<OAuthEventArgs>((o, args) =>
                {

                    if (args.IsError)
                    {
                        this.Dispatcher.BeginInvoke(() =>
                        {
                            twBlock.Visibility = Visibility.Collapsed;
                        });
                    }
                    else
                    {
                        Dictionary<string, string> results = Helpers.ParseQueryString(args.Response);
                        foreach (var item in results)
                        {
                            if (item.Key.Equals("oauth_token"))
                                m_twitterOAuth.Token = item.Value;
                            else if (item.Key.Equals("oauth_token_secret"))
                                m_twitterOAuth.TokenSecret = item.Value;
                        }

                        while (!m_browserLoaded)
                            Thread.Sleep(100);

                        this.Dispatcher.BeginInvoke(() =>
                        {
                            pinOkBtn.Visibility = Visibility.Visible;
                            twLogin.Navigate(new Uri(m_twitterOAuth.AuthenticationUrl));
                            twBlock.Visibility = Visibility.Visible;
                        });
                    }
                }));
        }

        private void loginOkBtn_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            twPinBlock.Visibility = Visibility.Visible;
        }

        private void pinCancelBtn_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            twPinBlock.Visibility = Visibility.Collapsed;
            
        }

        private void pinOkBtn_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            m_twitterOAuth.Verifier = pinTxt.Text;
            //SaveTwitterOAuth();
            try
            {
                Uri uri = new Uri(twLogin.Source.ToString());
                //parse the query string
                Dictionary<string, string> results = Helpers.ParseQueryString(uri.Query);
                foreach (var item in results)
                {
                    if (item.Key.Equals("oauth_verifier"))
                        m_twitterOAuth.Verifier = item.Value;
                    else
                    {          
                        twBlock.Visibility = Visibility.Collapsed;
                        twPinBlock.Visibility = Visibility.Collapsed;
                        MessageBox.Show("Twitter pin is wrong, please go back and try again.");
                        return;
                    }
                }
                //hide the web browser control
                this.Dispatcher.BeginInvoke(() =>
                {
                    // twLogin.Visibility = System.Windows.Visibility.Collapsed;
                });
                //now that we have the verifier get the access token
                OAuth.GetAccessToken(m_twitterOAuth.AccessTokenUrl,
                    m_twitterOAuth.ConsumerKey,
                    m_twitterOAuth.ConsumerSecret,
                    m_twitterOAuth.Token,
                    m_twitterOAuth.TokenSecret,
                    new EventHandler<OAuthEventArgs>((obj, args) =>
                    {
                        //handler when the get access token call returns
                        if (args.IsError)
                        {
                            this.Dispatcher.BeginInvoke(() => MessageBox.Show("Twitter pin is wrong, please go back and try again."));

                            //this.NavigationService.Navigate(new Uri("MainPage.xaml", UriKind.RelativeOrAbsolute));
                        }
                        else
                        {
                            //extract the items
                            results = Helpers.ParseQueryString(args.Response);
                            foreach (var item in results)
                            {
                                if (item.Key.Equals("oauth_token"))
                                    m_twitterOAuth.Token = item.Value;
                                else if (item.Key.Equals("oauth_token_secret"))
                                    m_twitterOAuth.TokenSecret = item.Value;
                                else if (item.Key.Equals("user_id"))
                                    m_twitterOAuth.UserId = item.Value;
                                else if (item.Key.Equals("screen_name"))
                                    m_twitterOAuth.ScreenName = item.Value;
                            }

                            //update the label
                            this.Dispatcher.BeginInvoke(() =>
                            {
                                if (this.publishImage != "")
                                {
                                    TweetPhotos();
                                    twBlock.Visibility = Visibility.Collapsed;
                                }
                                else
                                {
                                    if (!taxiNumber.Text.Equals(""))
                                    {
                                        PostTweet();
                                        twBlock.Visibility = Visibility.Collapsed;
                                    }
                                    else
                                    {
                                        MessageBox.Show("Please Enter Taxi Number");
                                        twBlock.Visibility = Visibility.Collapsed;
                                    }
                                }
                                twPinBlock.Visibility = Visibility.Collapsed;
                            });
                        }
                    }));
            }
            catch (Exception ex)
            {
                this.Dispatcher.BeginInvoke(() => MessageBox.Show(ex.Message));
            }
        }

        private void PostTweet()
        {
            //MessageBox.Show(lblTweet.Text);
            if (false)
            {
                MessageBox.Show("Message is greater than 140.  Cannot post");
            }
            else
            {
                string imageNames = "";

                imageNames = this.publishImage;
                try
                {
                    OAuth.GetProtectedResource(
                        string.Format(m_twitterOAuth.StatusUpdateUrl, HttpUtility.UrlEncode("กำลังอยู่บนรถแท๊กซี่, " + taxCol + ", " + taxiNumber.Text + ". #TAXILISM")),
                        "POST",
                        m_twitterOAuth.ConsumerKey,
                        m_twitterOAuth.ConsumerSecret,
                        m_twitterOAuth.Token,
                        m_twitterOAuth.TokenSecret,
                        new EventHandler<OAuthEventArgs>((obj, args) =>
                        {
                            if (args.IsError)
                                this.Dispatcher.BeginInvoke(() => MessageBox.Show(args.ErrorMessage));
                            else
                            {
                                this.Dispatcher.BeginInvoke(() =>
                                {
                                    //MessageBox.Show(args.Response, "Tweet Posted", MessageBoxButton.OK);
                                    MessageBox.Show("Post completed");
                                    captureBlock.Background = null;
                                    this.publishImage = "";
                                    taxiNumber.Text = "";
                                });
                            }
                        }));
                    ApplicationSettings.TwitterOAuthAppSettings = m_twitterOAuth;
                }
                catch (Exception error)
                {
                    MessageBox.Show("Sorry, there's an error occured, please try again.");
                }
            }
        }

        private void TweetPhotos()
        {
            string imageText = "";
            string ct = "image/jpg";
            string usertoken = m_twitterOAuth.Token;
            string userSecret = m_twitterOAuth.TokenSecret;
            string conkey = m_twitterOAuth.ConsumerKey;
            string consecret = m_twitterOAuth.ConsumerSecret;
            string twitkey = "5df897b5da6aeb289ac8dd7ffc78ed29";
            if (!taxiNumber.Text.Equals(""))
            {
                imageText = "กำลังอยู่บนรถแท๊กซี่, " + taxCol + ", " + taxiNumber.Text + ".";
            }
            else
            {
                imageText = "กำลังอยู่บนรถแท๊กซี่, " + taxCol + ".";
            }

            byte[] imageDatas = new byte[sri.Stream.Length];
            sri.Stream.Read(imageDatas, 0, System.Convert.ToInt32(sri.Stream.Length));

            string encoding = "iso-8859-1";
            //string fileData = Encoding.GetEncoding("iso-8859-1").GetString(imageDatas);

            TwitPic tw = new TwitPic();
            tw.UploadPhoto(imageDatas, ct, imageText, this.publishImage, twitkey, usertoken, userSecret, conkey, consecret);
            ApplicationSettings.TwitterOAuthAppSettings = m_twitterOAuth;
            MessageBox.Show("Post completed");
            captureBlock.Background = null;
            this.publishImage = "";
            taxiNumber.Text = "";
        }
        private void twLogin_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {

        }
        #endregion

        #region Camera
        private CameraCaptureTask cam;
        private void captureBlock_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            try
            {             
                cam.Show();
            }
            catch (System.InvalidOperationException ex) {
                MessageBox.Show(ex.Message);
            }
        }

        private string publishImage = "";
        public BitmapImage bmp = new BitmapImage();
        Image imgTweet = new Image();
        void cam_Completed(object sender, PhotoResult e) {
            if (e.TaskResult != TaskResult.OK) {
                return;
            }

            bmp.SetSource(e.ChosenPhoto);
			ImageBrush tmp = new ImageBrush();
            imgTweet.Source = bmp;
			tmp.ImageSource=bmp;
            this.publishImage = e.OriginalFileName;

            string imageName = "";
            imageName = this.publishImage;
            Uri jpegUri = new Uri(imageName, UriKind.Relative);
            sri = Application.GetResourceStream(jpegUri);

			captureBlock.Background=tmp;
        }
        #endregion
		
        #region FarePath

        bool checkSameIndex_from=false;
		bool checkSameIndex_to=false;
        private void fromLB_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
        	// about animation
			
			//fromLBhide.Begin();
			
			// end animation
            fromLB.Visibility = Visibility.Collapsed;
			fromLB.ApplyTemplate();
            if (fromLB.SelectedIndex != -1) {
				fromLBhide.Begin();
                var tmp = (sender as ListBox).SelectedItem as googlePlace;
                fromTxt.ActualHintVisibility = System.Windows.Visibility.Collapsed;
                fromTxt.Text = tmp.Data_description;
                fromTxt.Tag = tmp.Data_term;

                if (fromLB.Visibility == Visibility.Collapsed && toLB.Visibility == Visibility.Collapsed)
                {
                    waitScr.Visibility = Visibility.Visible;
                    pathLB.ItemsSource = null;
                    if (!fromTxt.Text.Contains("Your location") && toTxt.Text.Contains("Your location"))
                    {
                        //fc3.feedPlace(fromTxt.Text, toPosition);
                        fc3.feedPlace(fromTxt.Tag.ToString(), toPosition);
                    }
                    else
                    {
                        //fc3.feedPlace(fromTxt.Text, toTxt.Text);
                        fc3.feedPlace(fromTxt.Tag.ToString(), toTxt.Tag.ToString());
                    }
                    Dispatcher.BeginInvoke(() =>
                    {
                        t3 = new Thread(place_check);
                        t3.Start();
                    });
                }
                //Border bchild = VisualTreeHelper.GetChild((DependencyObject)fromLB.SelectedItem, 0) as Border;
                //TextBlock place = bchild.FindName("placeTxt") as TextBlock;
                //fromTxt.ActualHintVisibility = System.Windows.Visibility.Collapsed;
                //fromTxt.Text = place.Text;
            }
			
			
        }

        private void toLB_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
        	// about animation
			
			//toLBhide.Begin();
			
			// end animation
            toLB.Visibility = Visibility.Collapsed;
            toLB.ApplyTemplate();
            if (toLB.SelectedIndex != -1)
            {
                toLBhide.Begin();
                var tmp = (sender as ListBox).SelectedItem as googlePlace;
                toTxt.ActualHintVisibility = System.Windows.Visibility.Collapsed;
                toTxt.Text = tmp.Data_description;
                toTxt.Tag = tmp.Data_term;

                if (fromLB.Visibility == System.Windows.Visibility.Collapsed && toLB.Visibility == System.Windows.Visibility.Collapsed)
                {
                    waitScr.Visibility = Visibility.Visible;
                    pathLB.ItemsSource = null;
                    if (fromTxt.Text.Contains("Your location") && !toTxt.Text.Contains("Your location"))
                    {
                        //fc3.feedPlace(fromPosition, toTxt.Text);
                        fc3.feedPlace(fromPosition, toTxt.Tag.ToString());
                    }
                    else
                    {
                        //fc3.feedPlace(fromTxt.Text, toTxt.Text);
                        fc3.feedPlace(fromTxt.Tag.ToString(), toTxt.Tag.ToString());
                    }
                    Dispatcher.BeginInvoke(() =>
                    {
                        t3 = new Thread(place_check);
                        t3.Start();
                    });
                }
                //Border bchild = VisualTreeHelper.GetChild((DependencyObject)toLB.SelectedItem, 0) as Border;
                //TextBlock place = bchild.FindName("placeTxt") as TextBlock;
                //toTxt.ActualHintVisibility = System.Windows.Visibility.Collapsed;
                //toTxt.Text = place.Text;
            }
        }

        
        Thread t1,t2,t3;
        SearchPlaceFunction fc1 = new SearchPlaceFunction();
        SearchPlaceFunction fc3 = new SearchPlaceFunction();
        SearchPathFunction fc2 = new SearchPathFunction();
        private void getFareBtn_Click(object sender, RoutedEventArgs e)
        {
            if (NetworkInterface.NetworkInterfaceType != Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.None)
            {
                adviceBlock.Visibility = System.Windows.Visibility.Collapsed;
                if (fromTxt.Text != "" & toTxt.Text != "")
                {
                    waitScr.Visibility = Visibility.Visible;
                    fromLB.ItemsSource = null;
                    toLB.ItemsSource = null;
                    pathLB.ItemsSource = null;
                    fc1.feedAuto(fromTxt.Text, toTxt.Text);
                    //fc2.feedPath(fromTxt.Text, toTxt.Text);

                    Dispatcher.BeginInvoke(() =>
                    {
                        t1 = new Thread(t_check);
                        t1.Start();
                    });
                    //fromLB.Visibility = System.Windows.Visibility.Visible;
                    //toLB.Visibility = System.Windows.Visibility.Visible;
                }
                else
                {
                    MessageBox.Show("Please input your needed place.");
                }
            }
            else 
            {
                MessageBox.Show("Please check your internet connection.");
            }
        }

        public void t_check()
        {
            while (fc1.cnt_client != 0)
            {
                Thread.Sleep(100);
            }

            Dispatcher.BeginInvoke(() =>
            {
                //if (fc2.list_path.Count == 0)
                

                //{
                if (fromTxt.Text.Contains("Your location") && toTxt.Text.Contains("Your location"))
                {
                    waitScr.Visibility = Visibility.Visible;
                    pathLB.ItemsSource = null;
                    fc2.feedPath(fromPosition, toPosition);
                    Dispatcher.BeginInvoke(() =>
                    {
                        t2 = new Thread(path_check);
                        t2.Start();
                    });
                }
                else if (fromTxt.Text.Contains("Your location") && !toTxt.Text.Contains("Your location"))
                {
                    if (fc1.to_list_place.Count == 0)
                    {
                        MessageBox.Show("Your place was not found, please try again.");
                    }
                    else {
                        toLB.ItemsSource = fc1.to_list_place;
                        toLB.Visibility = System.Windows.Visibility.Visible;
                    }
                }
                else if (!fromTxt.Text.Contains("Your location") && toTxt.Text.Contains("Your location"))
                {
                    if (fc1.from_list_place.Count == 0)
                    {
                        MessageBox.Show("Your place was not found, please try again.");
                    }
                    else {
                        fromLB.ItemsSource = fc1.from_list_place;
                        fromLB.Visibility = System.Windows.Visibility.Visible;
                    }
                }
                else
                {
                    if (fc1.from_list_place.Count == 0 && fc1.to_list_place.Count == 0)
                    {
                        MessageBox.Show("Your place was not found, please try again.");
                    }
                    else if (fc1.from_list_place.Count == 0)
                    {
                        MessageBox.Show("Your place was not found, please try again.");
                        toLB.ItemsSource = fc1.to_list_place;
                        toLB.Visibility = System.Windows.Visibility.Visible;
                    }
                    else if (fc1.to_list_place.Count == 0)
                    {
                        MessageBox.Show("Your place was not found, please try again.");
                        fromLB.ItemsSource = fc1.from_list_place;
                        fromLB.Visibility = System.Windows.Visibility.Visible;
                    }
                    else {
                        fromLB.ItemsSource = fc1.from_list_place;
                        toLB.ItemsSource = fc1.to_list_place;
                        fromLB.Visibility = System.Windows.Visibility.Visible;
                        toLB.Visibility = System.Windows.Visibility.Visible;
                    }
                }
                //}
                //else
                //{
                    //fromLB.ItemsSource = fc1.from_list_place;
                    //toLB.ItemsSource = fc1.to_list_place;
                    //pathLB.ItemsSource = fc2.list_path;
                    //fromLB.Visibility = System.Windows.Visibility.Visible;
                    //toLB.Visibility = System.Windows.Visibility.Visible;
                //}
                    waitScr.Visibility = Visibility.Collapsed;
            });
            t1.Join();
            
        }

        public void path_check()
        {
            while (fc2.cnt_client != 0)
            {
                Thread.Sleep(100);
            }

            Dispatcher.BeginInvoke(() =>
            {
                //if (fc2.list_path.Count == 0)
                //{
                //}
                //else
                //{
                //fromLB.ItemsSource = fc1.from_list_place;
                //toLB.ItemsSource = fc1.to_list_place;
                SuggestText.Visibility = Visibility.Visible;
                fc2.list_path.OrderBy(googlePath => googlePath.Data_calFare);
                pathLB.IsEnabled = true;
                pathLB.ItemsSource = fc2.list_path;
                //fromLB.Visibility = System.Windows.Visibility.Visible;
                //toLB.Visibility = System.Windows.Visibility.Visible;
                //}
                waitScr.Visibility = Visibility.Collapsed;
            });
            t2.Join();
        }
        string fromPlacePoint;
        string toPlacePoint;
        public void place_check() 
        {
            while (fc3.cnt_client != 0)
            {
                Thread.Sleep(100);
            }
            googleLatLong frompoint = new googleLatLong();
            googleLatLong topoint = new googleLatLong();

            Dispatcher.BeginInvoke(() =>
            {
                
                if (fc3.from_list_point.Count() != 0) 
                {  
                    frompoint = fc3.from_list_point.First();
                    fromPlacePoint = frompoint.Data_lat.ToString() + "," + frompoint.Data_long.ToString();
                }
                else if (fc3.from_list_point.Count() == 0)
                {
                    fromPlacePoint = fromTxt.Text.ToString();
                }
                if (fc3.to_list_point.Count() != 0) 
                { 
                    topoint = fc3.to_list_point.First();
                    toPlacePoint = topoint.Data_lat.ToString() + "," + topoint.Data_long.ToString();
                }
                else if (fc3.to_list_point.Count() == 0)
                {
                    toPlacePoint = toTxt.Text.ToString();
                }

                if (!fromTxt.Text.Contains("Your location") && toTxt.Text.Contains("Your location"))
                {
                    fc2.feedPath(fromPlacePoint, toPosition);
                }
                else if (fromTxt.Text.Contains("Your location") && !toTxt.Text.Contains("Your location"))
                {
                    fc2.feedPath(fromPosition, toPlacePoint);
                }
                else if (fromTxt.Text.Contains("Your location") && toTxt.Text.Contains("Your location"))
                {
                    fc2.feedPath(fromPosition, toPosition);
                }
                else
                {
                    fc2.feedPath(fromPlacePoint, toPlacePoint);
                }

                Dispatcher.BeginInvoke(() =>
                {
                    t2 = new Thread(path_check);
                    t2.Start();
                });
            });
            t3.Join();
        }

        private void viewPathBtn_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            pathImg.Source = null;
            Button t = (Button)sender;
            string uri = "http://maps.googleapis.com/maps/api/staticmap?size=640x640&scale=2&sensor=true&format=jpg&path=color:0xff0000ff|weight:5|enc:" + t.Tag;
            pathImg.Navigate(new Uri(uri));
            imgBlock.Visibility = System.Windows.Visibility.Visible;		
        }

        private void closeImgBlock_Click(object sender, System.Windows.RoutedEventArgs e)
        {
        	// TODO: Add event handler implementation here.
			imgBlock.Visibility=System.Windows.Visibility.Collapsed;
        }


        Thread t5;
        int idRecent;
      
        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e) //ดัก event เวลากดปุ่ม back ที่เครื่อง
        {           
            if (fbLogin.Visibility == Visibility.Visible)
            {
                fbLogin.Visibility = Visibility.Collapsed;
                e.Cancel = true;
            }
            if (twBlock.Visibility == Visibility.Visible)
            {
                twBlock.Visibility = Visibility.Collapsed;
                twPinBlock.Visibility = Visibility.Collapsed;
                e.Cancel = true;
            }
        }
        #endregion

        #region getPostition
        double myLatitude;
        double myLongitude;
        GeoCoordinateWatcher fromWatcher;
        GeoCoordinateWatcher toWatcher;
        private void fromTxt_ActionIconTapped(object sender, System.EventArgs e)
        {
        	// TODO: Add event handler implementation here.
            if (checkAllowLocation)
            {

                fromWatcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default);
                fromWatcher.MovementThreshold = 10;

                fromWatcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(fromWatcher_PositionChanged);
                fromWatcher.Start();
            }
            else
            {
                MessageBoxResult result = MessageBox.Show("This action will enable Location Service and collect your location data as an input of textbox and then it will disable Location Service and use your location data to calculate a fare when you press a Get fare button. This action doesn't sharing your location data anyway.", "Allow the application to use your location?", MessageBoxButton.OKCancel);
                if (result == MessageBoxResult.OK)
                {
                    la.putAllow("true");
                    la.getAllow();
                    checkAllowLocation = Convert.ToBoolean(la.status);

                    
                    fromWatcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default);
                    fromWatcher.MovementThreshold = 10;

                    fromWatcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(fromWatcher_PositionChanged);               
                    fromWatcher.Start();
                }
            }
        }

        private void toTxt_ActionIconTapped(object sender, System.EventArgs e)
        {
        	// TODO: Add event handler implementation here.
            if (checkAllowLocation)
            {
                
                toWatcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default);
                toWatcher.MovementThreshold = 10;

                toWatcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(toWatcher_PositionChanged);
                toWatcher.Start();
            }
            else
            {
                MessageBoxResult result = MessageBox.Show("This action will enable Location Service and collect your location data as an input of textbox and then it will disable Location Service and use your location data to calculate a fare when you press a Get fare button. This action doesn't sharing your location data anyway.", "Allow the application to use your location?", MessageBoxButton.OKCancel);
                if (result == MessageBoxResult.OK)
                {
                    la.putAllow("true");
                    la.getAllow();
                    checkAllowLocation = Convert.ToBoolean(la.status);

                    
                    toWatcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default);
                    toWatcher.MovementThreshold = 10;

                    toWatcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(toWatcher_PositionChanged);
                    toWatcher.Start();

                }
            }
        }

        void fromWatcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() => ChangeFromPos(e));
        }

        void ChangeFromPos(GeoPositionChangedEventArgs<GeoCoordinate> e) 
        {
            myLatitude = e.Position.Location.Latitude;
            myLongitude = e.Position.Location.Longitude;
            fromPosition = myLatitude.ToString() + "," + myLongitude.ToString();
            fromTxt.ActualHintVisibility = System.Windows.Visibility.Collapsed;
            fromTxt.Text = "Your location";
            //fromWatcher.Stop();
            //fromWatcher.Dispose();
        }

        void toWatcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() => ChangeToPos(e));
        }

        string toPosition, fromPosition;
        void ChangeToPos(GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            myLatitude = e.Position.Location.Latitude;
            myLongitude = e.Position.Location.Longitude;
            toPosition = myLatitude.ToString() + "," + myLongitude.ToString();
            toTxt.ActualHintVisibility = System.Windows.Visibility.Collapsed;
            toTxt.Text = "Your location";
            //toWatcher.Stop();
            //toWatcher.Dispose();
        }
        #endregion

        #region settings
        private void closeTipBtn_Click(object sender, System.Windows.RoutedEventArgs e)
        {
        	// TODO: Add event handler implementation here.
			adviceBlock.Visibility=System.Windows.Visibility.Collapsed;
        }

        private void helpBtn_Click(object sender, System.Windows.RoutedEventArgs e)
        {
        	// TODO: Add event handler implementation here.
			adviceBlock.Visibility=System.Windows.Visibility.Visible;
        }

        private void settingBtn_Click(object sender, System.EventArgs e)
        {
        	// TODO: Add event handler implementation here.
            goSetting = 1;
			NavigationService.Navigate(new Uri("/setting.xaml", UriKind.RelativeOrAbsolute));
        }
        #endregion

        #region rate
        private void rateBtn_Click(object sender, RoutedEventArgs e)
        {
            rateBlock.Visibility = Visibility.Visible;
        }

        private void rate1_btn_Click(object sender, RoutedEventArgs e)
        {
            rateBlock.Visibility = Visibility.Collapsed;
            TaxNum.delVoteable(idRecent, "System.Windows.Visibility.Collapsed");
            TaxNum.putRate(idRecent, 1);
            
            Dispatcher.BeginInvoke(() =>
            {
                t5 = new Thread(taxilistrate_check);
                t5.Start();
            });
        }

        private void rate2_btn_Click(object sender, RoutedEventArgs e)
        {
            rateBlock.Visibility = Visibility.Collapsed;
            TaxNum.delVoteable(idRecent, "System.Windows.Visibility.Collapsed");
            TaxNum.putRate(idRecent, 2);

            Dispatcher.BeginInvoke(() =>
            {
                t5 = new Thread(taxilistrate_check);
                t5.Start();
            });
        }

        private void rate3_btn_Click(object sender, RoutedEventArgs e)
        {
            rateBlock.Visibility = Visibility.Collapsed;
            TaxNum.delVoteable(idRecent, "System.Windows.Visibility.Collapsed");
            TaxNum.putRate(idRecent, 3);

            Dispatcher.BeginInvoke(() =>
            {
                t5 = new Thread(taxilistrate_check);
                t5.Start();
            });
        }

        private void rate4_btn_Click(object sender, RoutedEventArgs e)
        {
            rateBlock.Visibility = Visibility.Collapsed;
            TaxNum.delVoteable(idRecent, "System.Windows.Visibility.Collapsed");
            TaxNum.putRate(idRecent, 4);

            Dispatcher.BeginInvoke(() =>
            {
                t5 = new Thread(taxilistrate_check);
                t5.Start();
            });
        }

        private void rate5_btn_Click(object sender, RoutedEventArgs e)
        {
            rateBlock.Visibility = Visibility.Collapsed;
            TaxNum.delVoteable(idRecent, "System.Windows.Visibility.Collapsed");
            TaxNum.putRate(idRecent, 5);

            Dispatcher.BeginInvoke(() =>
            {
                t5 = new Thread(taxilistrate_check);
                t5.Start();
            });
        }

        private void cancelRate_btn_Click(object sender, RoutedEventArgs e)
        {
            rateBlock.Visibility = Visibility.Collapsed;
        }
        #endregion

        private void serviceCallBtn_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (NetworkInterface.NetworkInterfaceType != Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.None)
            {
                int id = Convert.ToInt32((sender as Button).Tag.ToString());
                TaxNum.putVoteable(id, "System.Windows.Visibility.Visible");
                RecentCallListBox.IsEnabled = true;
                Button t = (Button)sender;
                idRecent = Convert.ToInt32(t.Tag);
                CallTaxiNumber taxiRe = new CallTaxiNumber();
                taxiRe.putRecent(id);
                taxiRe.getRecent();
                TaxNum.putRecent(id);
                taxiRe.feedTaxi();
                TaxNum.getVoteable();
                TaxNum.getRateShow();

                PhoneCallTask tel = new PhoneCallTask();
                foreach (TaxiList rs in taxiRe.taxi_list)
                {
                    if (rs.Data_id.Equals(t.Tag))
                    {
                        tel.PhoneNumber = rs.Data_taxPhone;
                        tel.DisplayName = rs.Data_taxName;
                    }
                }
                Dispatcher.BeginInvoke(() =>
                {
                    t5 = new Thread(taxilistrate_check);
                    t5.Start();
                });

                tel.Show();
            }
            else
            {
                int id = Convert.ToInt32((sender as Button).Tag.ToString());
                TaxNum.putRecent(id);
                TaxNum.feedTaxi();
                TaxNum.getRecent();
                RecentCallListBox.ItemsSource = null;
                RecentCallListBox.IsEnabled = true;
                Button t = (Button)sender;
                idRecent = Convert.ToInt32(t.Tag);
                foreach (TaxiList list in TaxNum.taxi_list)
                {
                    if (list.Data_id == idRecent.ToString())
                    {
                        List<TaxiList> reallist = new List<TaxiList>();
                        reallist.Add(list);
                        RecentCallListBox.ItemsSource = reallist;
                    }
                }
                PhoneCallTask tel = new PhoneCallTask();
                foreach (TaxiList rs in TaxNum.taxi_list)
                {
                    if (rs.Data_id.Equals(t.Tag))
                    {
                        tel.PhoneNumber = rs.Data_taxPhone;
                        tel.DisplayName = rs.Data_taxName;
                    }
                }
                tel.Show();
            }
        }

    }
}
